﻿//-----------------------------------------------------------------------
// <copyright file="PsExec.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Andy Reeves [Updated: M Fourie - 2008-02-12</author>
// <email>andyr</email>
// <date>2004-03-23</date>
// <summary>Executes a command on a remote machine.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Sdc.Tasks.Tools
{
    using System;
    using System.IO;
    using Microsoft.Build.Framework;
    using Microsoft.Build.Tasks;

    /// <summary>
    /// Executes PsExec.exe (available from www.sysinternals.com ) in order to execute a command on a remote machine.
    /// </summary>          
    /// <remarks>
    /// <code><![CDATA[
    /// <Tools.PsExec ToolPath="toolPath"
    ///                WorkingDirectory="workingDirectory"
    ///                   Command="command"
    ///                   Server="server"
    ///                   User="user"
    ///                   Password="password"
    ///                   LoadProfile="loadProfile">
    /// </Tools.Sn>
    /// ]]></code>
    /// <para>where:</para>
    /// <para><i>toolPath (Required)</i></para>
    /// <para>The path to the folder where PsExec.exe can be found on the local machine.</para>
    /// <para><i>workingDirectory (Optional)</i></para>
    /// <para>The working directory the remote process should use.</para>
    /// <para><i>command (Required)</i></para>
    /// <para>The command to execute on the remote machine.</para>
    /// <para><i>server (Required)</i></para>
    /// <para>The remote machine on which the command should be executed.</para>
    /// <para><i>user (Required)</i></para>
    /// <para>The domain\user that should be used on the remote machine.</para>
    /// <para><i>password (Required)</i></para>
    /// <para>The password of the user that should be used on the remote machine.</para>
    /// <para><i>loadProfile (Optional)</i></para>
    /// <para>If set to 'true' the profile of the user specified by user is loaded when executing the remote command.</para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <Tools.PsExec
    ///             ContinueOnError="true"
    ///             ToolPath="c:\PsTools" 
    ///             Command="cmd /c mkdir c:\testdir"
    ///                Server="MyRemoteMachine"
    ///                User="MyAdminUser"
    ///                Password="MyAdminPassword"
    ///         </Tools.PsExec> 
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public sealed class PsExec : ToolTaskBase
    {
        private string command;
        private string workingDirectory;
        private string server;
        private string user;
        private string password;
        private bool loadProfile;

        /// <summary>
        /// The command to execute on the remote machine.
        /// </summary>
        /// <value>The command.</value>
        [Required]
        public string Command
        {
            get { return this.command ?? String.Empty; }
            set { this.command = value; }
        }

        /// <summary>
        /// THe folder to set the working directory to on the remote machine.
        /// </summary>
        /// <value>The working directory.</value>
        public string WorkingDirectory
        {
            get { return this.workingDirectory ?? String.Empty; }
            set { this.workingDirectory = value; }
        }

        /// <summary>
        /// The name of the remote machine.
        /// </summary>
        /// <value>The server.</value>
        [Required]
        public string Server
        {
            get
            {
                return this.server ?? String.Empty;
            }

            set
            {
                if (value.Contains(@"\\") || value.StartsWith(@"\"))
                {
                    throw new ArgumentException("The server name cannot begin with '\' or contain '\\'");
                }

                this.server = value;
            }
        }

        /// <summary>
        /// The username to use on the remote machine when running the command.
        /// </summary>
        /// <value>The user.</value>
        public string User
        {
            get { return this.user ?? String.Empty; }
            set { this.user = value; }
        }

        /// <summary>
        /// The password of the remote user.
        /// </summary>
        /// <value>The password.</value>
        public string Password
        {
            get { return this.password ?? String.Empty; }
            set { this.password = value; }
        }

        /// <summary>
        /// True to force the profile of the remote user to be loaded on the remote machine.
        /// </summary>
        /// <value><c>true</c> if [load profile]; otherwise, <c>false</c>.</value>
        public bool LoadProfile
        {
            get { return this.loadProfile; }
            set { this.loadProfile = value; }
        }

        /// <summary>
        /// The name of the exe we call.
        /// </summary>
        /// <value>The name of the exe we call.</value>
        /// <returns>The name of the executable file to run.</returns>
        protected override string ToolName
        {
            get { return "PsExec.exe"; }
        }

        /// <summary>
        /// Full calculated path to tool including exe name
        /// </summary>
        /// <returns>The full path to PsExec.exe</returns>
        protected override string GenerateFullPathToTool()
        {
            string pathToTool = Path.Combine(this.ToolPath, this.ToolName);

            if (pathToTool == null)
            {
                Log.LogMessage(MessageImportance.High, "PsExec.NotFound");
            }

            return pathToTool;
        }

        /// <summary>
        /// Builds the commandline for this tool
        /// </summary>
        /// <param name="commandLine">The object to append the args to.</param>
        protected override void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
        {
            commandLine.AppendSwitch(@"\\" + this.Server);

            if (!string.IsNullOrEmpty(this.User))
            {
                commandLine.AppendSwitch("-u " + this.User);
                commandLine.AppendSwitch("-p " + this.Password);
            }

            if (this.LoadProfile)
            {
                commandLine.AppendSwitch("-e");
            }

            if (this.WorkingDirectory.Length > 0)
            {
                commandLine.AppendSwitch("-w " + this.WorkingDirectory);
            }

            commandLine.AppendSwitch(this.Command);
        }
    }
}
